import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common';
import { Request } from 'express';
import { format } from 'date-fns';

@Catch()
export class WorkFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const request = ctx.getRequest<Request>();
    const response = ctx.getResponse();

    let code: number;
    let msg: string;

    // 处理 HttpException
    if (exception instanceof HttpException) {
      code = exception.getStatus();
      msg = exception.message;
    } else {
      // 处理其他类型的异常
      code = HttpStatus.INTERNAL_SERVER_ERROR;
      msg = '系统异常，请稍后再试';
    }

    // 格式化当前时间
    const time = format(new Date(), 'yyyy-MM-dd HH:mm:ss');

    response.status(code).json({
      code,
      msg,
      requestUrl: `${request.protocol}://${request.get('host')}${request.originalUrl}`,
      time,
    });
  }
}